<template>
  <div>
    <!-- 玩法说明 -->
    <Guide :isShow="state.guideVisible" @handleClose="state.guideVisible = false" />

    <div class="game-top">
      <div class="go_home" @click="goHome">返 回</div>
      <!-- <div class="u_num">
        <img :src="assetsImageUrl + 'images/u_num.png'" alt="" />
        {{state.u_num}}U星能
      </div> -->
    </div>
    <div>
      <!-- 进度条 -->
      <div class="jumping_load" id="J_loadLayer" v-if="state.showLoad">
        <div class="center">
          <div class="robot"></div>
          <div class="process">
            <div class="curr_process"></div>
          </div>
        </div>
      </div>

      <!-- S 主舞台 -->
      <div class="jumping_game" id="phaser" ref="phaser">
        <div class="bg_box">
        </div>
      </div>
    </div>

    <div class="footer">
      <!-- <div class="ranking" @click="goRanking"><img :src="assetsImageUrl + '/images/ranking.png'" alt="" />
        <div class="btn">
          排名
        </div>
      </div> -->
      <div class="dice"></div>
      <!-- <div class="ranking prizebox">
        <img :src="assetsImageUrl+'/images/ranking.png'" alt="" class="ranking-right-img">
        <img class="prize-icon" v-show="state.endData.category === 7" :src="assetsImageUrl + '/images/prize-2.png'" alt="" />
        <img class="prize-icon" v-show="state.endData.category === 0" :src="assetsImageUrl + '/images/prize-4.png'" alt="" />
        <img class="prize-icon"  v-show="state.endData.category === 6" :src="assetsImageUrl + '/images/prize-5.png'" alt="" />
        <img class="prize-icon"  v-show="state.endData.category === 3" :src="assetsImageUrl + 'images/reward_icon3.png'" alt="" />
        <img class="prize-icon"  v-show="[3,4].includes(state.endData.category)" :src="assetsImageUrl + '/images/prize-3.png'" alt="" />
      </div> -->
      <div class="roll_dice" @click="handleRollDice">
        <img :src="assetsImageUrl + '/images/roll_dice.png'" alt="">
        <!-- <p class="remain-times">今日剩余{{ state.numTimes }}次机会</p> -->
      </div>
      <!-- <div class="box_shadow"><div class="tr_t">开启挑战</div></div> -->
    </div>

    <!-- 奖励弹窗 -->
    <ResultPopover
      :title="state.popoverTitle"
      :isShow="state.myPopoverPage"
      :tips="state.popoverTips"
      :icon="state.popoverIcon"
      :get-remain-game-num="state.get_remain_game_num"
      :show-share="state.showShare"
      @showShareModal="showShareModal"
      @handleClose="handleClose">
      <template v-if="state.popoverTips">本次投掷获得<br /></template>
      <div v-html="state.popoverMsg"></div>
    </ResultPopover>
    <UniPopover 
    :isShow="state.uniTypeShow"
    @handle-close="handleConfirmCarType"
    />
    <!-- <share
      :is-show="state.shareModal"
      :share-img="state.shareImg"
      @handle-close="state.shareModal=false"
    /> -->
    <GameOver 
      :showShare="state.showShare"
      :is-show="state.showGameOver"
      :title="state.popoverTitle"
      :icon="state.popoverIcon"
      close
      @handle-close="state.showGameOver = false"
    >
    <div v-html="state.gameTips"></div>
  </GameOver>
  <audio  :src="assetsImageUrl+'/audio/clearday.mp3'" style="display: none;"  ref="audioRef"></audio>
  </div>
</template>

<script setup>
import { showToast, showLoadingToast, closeToast } from 'vant';
import 'vant/es/toast/style';
import { reactive, ref, onMounted, nextTick, onBeforeUnmount } from "vue";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import MyPopover from "../components/MyPopover.vue";
import Guide from '../components/guide.vue';
import "../assets/css/game/index.css";
import gameAll from "../assets/js/game/main.js";

import { gameTimes, gameStart, gameEnd, getScore, userQrcode } from "../api/index"
import UniPopover from '../components/UniPopover.vue';
import share from '../components/share.vue';
import ResultPopover from '../components/ResultPopover.vue'
import utils from '../utils';
const route = useRouter();
const assetsImageUrl = ref(import.meta.env.VITE_ASSETS_IMAGE_URL)
const audioRef = ref()
const state = reactive({
  loading: false,
  numTimes: 10,
  // successPage: false,
  myPopoverPage: false,
  guideVisible: false,
  showLoad: true,
  isShow: false,
  game: {},
  popoverTitle: '',
  popoverIcon: '',
  popoverMsg: '',
  popoverTips: false,
  endData: {},
  u_num: 0,
  uniTypeShow: false,
  get_remain_game_num: 0,
  showShare: false,
  shareModal:false,
  close: false,
  shareImg: '',
  showGameOver: false,
    gameTips: '',
});

function goHome() {
  route.push('/');
}

function goRanking() {
  route.push("/ranking");
}

const progressCallback = (data) => {
  
  // if (utils.getUserInfo())
  state.guideVisible = true;
  state.showLoad = false;
  
  
}

const handleConfirmCarType = () => {
  state.uniTypeShow = false
  nextTick(() => {
    state.guideVisible = true
  })
}
// 点击投掷按钮
async function handleRollDice() {
  if (state.loading) return;

  state.loading = true;
  if (state.numTimes < 1) {
    state.myPopoverPage = true;
    state.popoverTitle = '很遗憾'
    state.popoverMsg = '今日次数已用完，每邀请2名新人用户加入社群还可获得一次投掷骰子机会噢！'
    state.popoverIcon = assetsImageUrl.value+'/images/fail-icon.png'
    state.popoverTips = false
    state.showShare = true
    state.loading = false
    return;
  }

  // 开始游戏
  const startInfo = await setGameStart();
  if([1022,999].includes(startInfo.error_code)) {
    state.showGameOver = true
    state.popoverTitle = '很遗憾'
    state.popoverIcon = assetsImageUrl.value+'/images/fail-icon.png'
    state.gameTips = startInfo.msg
    state.loading = false
    return
  }
  if(startInfo.error_code === 1021) {
    state.gameTips = startInfo.msg
    state.showShare = true
    state.popoverIcon = assetsImageUrl.value+'/images/fail-icon.png'
    state.popoverTitle = '很遗憾'
    state.showGameOver = true
    state.loading = false
    return
  }
  if (startInfo.error_code === 1002) {
    state.myPopoverPage = true;
    state.popoverTitle = '很遗憾'
    state.popoverMsg = startInfo.msg
    state.popoverIcon = assetsImageUrl.value+'/images/fail-icon.png'
    state.popoverTips = false
    state.showShare = true
    state.loading = false
    return
  }

  // 设置骰子动画
  const dice = document.querySelector('.dice');
  dice.style.backgroundImage = `url(${import.meta.env.VITE_ASSETS_IMAGE_URL}/images/dice-s-2.gif)`;

  // 随机点数
  const count = Math.ceil(Math.random() * 6);

  // 设置骰子点数
  setTimeout(() => {
    dice.style.backgroundImage = `url(${import.meta.env.VITE_ASSETS_IMAGE_URL}/images/dice${count}.png)`;
  }, 800)

  // 调用结束接口
  const endData = await setGameEnd(count);
  state.popoverIcon = '';
  // state.popoverIcon = endData.icon;

  // 移动步数
  setTimeout(() => {
    state.game.spriteMove(count, endData.category, async function() {
      state.myPopoverPage = true;
      state.popoverTitle = '恭喜您'
      console.log(endData.category)
      state.popoverMsg = endData.category === 1 ? `${endData.name}` : `本次投掷获得${endData.name}`
      if(endData.category === 6) {
        state.popoverMsg = `本次投掷获得${endData.name}<br/>可额外投掷一次`
      }
      state.popoverIcon = assetsImageUrl.value+'/images/success-icon.png'

      state.popoverTips = false
      if (endData.category === 1) {
        state.popoverTips = true
      } else if (endData.category === 5) {
        state.popoverTitle = '很遗憾'
        // state.popoverIcon = ''
      }
      Object.assign(state, {...endData,loading:false})
      state.endData = { ...endData };

      await nextTick();
      // 获取最新u星能
      // fetchScore();
    });
    // getGameTimes();
  }, 900)
}

// 监听页面加载完成
window.addEventListener("progress", progressCallback);

function handleClose() {
  console.log(state)
  // state. = false;
  Object.assign(state, {
    myPopoverPage: false,
    popoverMsg: '',
    popoverIcon: ''
  })
  if (state.close) {
    Object.assign(state, {
    myPopoverPage: false,
    popoverMsg: '',
    popoverIcon: ''
  })
    return
  } else {
    state.close = false
  }
  nextTick(() => {
    console.log(111111)
    if (Object.keys(state.endData?.rank_exchange_dict??{}).length) {
      
      Object.assign(state,{
        category: 6,
        // ...Object.assign()
        popoverMsg: `${state.endData.rank_exchange_dict.extra}<br />获得${state.endData.rank_exchange_dict.name}`,
        popoverIcon: state.endData.rank_exchange_dict.icon,
        myPopoverPage:true,
        close:true

      })
      return
    } else {
      state.close = false
    }
    
  })
}

function showShareModal()  {
  state.myPopoverPage = false
  userQrcode().then((resp) => {
        // console.log(resp,'resp')
        Object.assign(state,{shareImg: resp.data.qrcode,shareModal:true})
      })
}

// 游戏开始
function setGameStart() {
  return new Promise(resolve => {
    gameStart().then(res => {
if (res.error_code ===1002) {
  
}
      resolve(res)
    })
  })
}

// 游戏结束
function setGameEnd(dice_num) {
  return new Promise(resolve => {
    gameEnd({ dice_num }).then(res => {
      const { data: { category, icon, name,get_remain_game_num } } = res;
      console.log(res,'resssppppppppp')
      // let newCategory = 1;

      // if (category === 0) {
      //   newCategory = 1;
      // } else if (category === 3 || category === 4) {
      //   newCategory = 4;
      // } else if (category === 6) {
      //   newCategory = 2;
      // } else if (category === 7) {
      //   newCategory = 3;
      //   // setTimeout(() => {
      //   //   // 获取最新u星能
      //   //   fetchScore();
      //   // }, 1000)
      // } else if (category === 5) {
      //   newCategory = 5;
      // }

      const endData = { ...res.data }

      resolve(endData);
    }).catch(e => {
      console.log(e,'errrr')
      state.myPopoverPage = true;
      state.popoverTitle = '很遗憾'
      state.popoverMsg = e.msg
      state.popoverIcon = ''
      state.popoverTips = false
    })
  })
}

// 获取游戏剩余次数
function getGameTimes() {
  gameTimes().then(res => {
    const { data = {} } = res
    // state.numTimes = data.remain_game_num || 0;
    state.loading = false;
  })
}

// 获取U星能
function fetchScore() {
  getScore().then(res => {
    state.u_num = res.data;
  })
}

onMounted(() => {
  // getGameTimes();
  // fetchScore();
  setTimeout(() => {
    state.game = new gameAll();
    state.game.init()
    audioRef.value.play()
  }, 10);
  console.log(state.game)
});
onBeforeUnmount(() => {
  audioRef.value.pause()
  audioRef.value.currentTime = 0
  try {
    window.removeEventListener("progress", progressCallback)
  } catch (error) {

  }

});
</script>

<style lang="scss" scoped>
.go_home,
.u_num {
  position: fixed;
  z-index: 99;
  top: 80px;
  height: 50px;
  background: rgb(198, 124, 74);
  /* box-shadow: 2px 5px 3px rgba(78, 129, 233, 1); */
  border-top-right-radius: 64px;
  border-bottom-right-radius: 64px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: "ChangAnunitype-Regular";
  font-size: 30px;
}
.go_home {
  
  left: 0;
  height: 80px;
  width: 150px;
  background: url(#{$base_path}/images/gohome-bg.png);
  background-size: 100% 100%;
  line-height: 80px;
}

.u_num {
  right: 20px;
  min-width: 200px;
  border-radius: 64px;
  padding-left: 25px;
}
.u_num > img {
  width: auto;
  height: 80px;
  position: absolute;
  left: -35px;
  margin-top: -5px;
}

.game-top {
  width: 100%;
  display: flex;
  height: 122px;
  justify-content: space-around;
  align-items: center;
  position: fixed;
  z-index: 9999;
}

.jumping_game {
  position: relative;
}

.bg_box {
  position: absolute;
  width: 100%;
  height: 100vh;
  z-index: -1;
  /* background: linear-gradient(183deg, #4c7de7 0, #1798da 20%); */
  // background: linear-gradient(183deg, #f99f48 0, #fbe8cd 60%);
  background-image: url(#{$base_path}/images/game-bg.png);
  background-size: 100% 100%;
}

.bg_box>img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.footer {
  position: absolute;
  bottom: -30px;
  width: 100%;
  height: 370px;
  background: url(#{$base_path}/images/game_footer.png) no-repeat;
  background-size: 100% 100%;
}

.footer  {
  .ranking,.prizebox {
    position: absolute;
  
  margin-left: -52px;
  margin-top: 40px;
  &>img {
    width: 153px;
  }
  }
  .ranking {
    left: 15%;
    &.prizebox {
      left: 80%;
      &>.ranking-right-img {
        width: 153px;
      }
    }
  }
  .prizebox {

    display: flex;
  justify-content: center;
  align-items: center;
  width: 153px;
  // height: 96px;
  // position: absolute;
  right: 15%;
  // margin-left: -52px;
  // margin-top: 66px;
  /* margin-right: -82px; */
  /* margin-top: 10px; */
  // background: url('');
  background-size: cover;
  }
  
}

// .footer .ranking>img {
//   width: 153px;
// }

.footer .prizebox {
  
}

.footer .prizebox img {
  width: 78px;
}

.footer .dice {
  position: absolute;
  left: 50%;
  width: 166px;
  height: 166px;
  background: url('https://yinli-qixi-run.varwey.com/2023_ca/u_chess/images/dice6.png');
  /* background-position: -770px 166px; */
  background-size: cover;
  margin-left: -83px;
  margin-top: -40px;
}

.footer .roll_dice {
  width: 279px;
  position: absolute;
  left: 50%;
  top: 50%;
  // margin-left: -140px;
  transform: translateX(-50%);
  text-align: center;
}

.footer .roll_dice>img {
  width: 100%;
}

.footer .roll_dice .remain-times {
  font-size: 18px;
  margin-top: 5px;
}

.text_active {
  color: #0160a5;
}

.score-num {
  flex: 1;
  justify-content: center;
  align-items: center;
  display: flex;
}
.prize-icon {
  margin-bottom: 44px;
}
</style>